//index.js
//获取应用实例
const app = getApp()
const util = require('../../utils/util.js')
var load = require('../../utils/ballLoading.js');

Page({
  data: {
    winWidth: 0,
    winHeight: 0,
    invoiceTab: '0', //发票列表 分类
    invoiceImg: false,
    searchDateTab: 1,
    searchDateMonthTab: null,
    showIntroduceDialog: false, //首次进入，展示海报控件
    showChooseDialog: false, //首次进入，选择vip以及单次使用控件
    userType: '', //用户等级
    top_swiper: '', // 发票类型筛选 class名，用作吸顶样式调控
    swiper_height: 0, //列表高度
    topxp: 170, // 滚动距离多少触发top_swiper 修改
    search: false, //搜索
    singPayStatus: true, //单次购买入口状态控制
    lodding: false,
    noData: false,
    showBallDialog: false, //展示球状加载动画
    ballText: '', //球状加载动画描述
    searchDate: [], //日期搜索中的日期列表
    invoiceList:[]
  },
  onShow: function () {
    var that = this
    //添加底部导航栏选中效果
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        selected: 0 //这个数是，tabBar从左到右的下标，从0开始
      })
    }
    var wxUserType = app.globalData.wxUserType
    if(that.data.showChooseDialog || that.data.showIntroduceDialog){
      if(wxUserType == '1' || wxUserType == '2' || wxUserType == '3'){ //非免费用户 关闭海报以及选择弹框
        that.setData({
          showIntroduceDialog: false,
          showChooseDialog: false
        })
      }
    }
  },
  onLoad: function (o) {
    var that = this;
    var shareId = o.wxUserId
    if(shareId != undefined){
      app.globalData.shareId = shareId
    }
    var wxUserId = app.globalData.wxUserId
    console.log("----------onLoad index-------------id：" + wxUserId)
    var searchDate = util.indexSearchDate()
    // 后台获取单次购买是否需要打开
    that.getSingPayStatus();
    // 根据当前用户id 以及用户权限等级，判断是否打开海报
    if(wxUserId != null && wxUserId != ''){
      app.http.get('/wechat/getUserType?wxUserId=' + wxUserId).then(res =>{
        var showIntroduceD = false
        var userType = ''
        if(res.status == '200'){
          console.log('--------wx user type:'+res.data +'----------')
          userType = res.data
          app.globalData.wxUserType = res.data
        } 
        that.setData({
          userType: userType,
          showChooseDialog: showIntroduceD,
          searchDate: searchDate,
          winWidth: app.globalData.winWidth,
          winHeight: app.globalData.winHeight
        })
        that.getInvoiceData()
      })
    } else { // 未登录 展示海报

      that.setData({
        showIntroduceDialog: true,
        searchDate: searchDate,
        winWidth: app.globalData.winWidth,
        winHeight: app.globalData.winHeight
      })
      that.getInvoiceData()
      setTimeout(function () { //5s 后自动关闭海报
        if(that.data.showIntroduceDialog){
          that.setData({
            showIntroduceDialog: false,
            showChooseDialog: true
          })
        }
      },5 * 1000);
    }
    
  },
  onShareAppMessage: function (res) {
    console.log("用户开始分享朋友", res)
    var wxUserId = app.globalData.wxUserId
    return {
      title: "邀请你使用电子发票",
      path:'/pages/index/index?wxUserId=' + wxUserId,
      imageUrl: '/pages/resource/images/share.png',
      success: function (res) {console.log("转发朋友成功", res)},
      fail: function (res) {
        // 转发失败
        console.log("用户点击了取消", res)
      } 
    }
  },
  onShareTimeline: function(res) { //分享朋友圈
    var wxUserId = app.globalData.wxUserId
    console.log("用户开始分享朋友圈", res)
    return {
      title: "邀请你使用电子发票",
      query: "wxUserId=" + wxUserId,
      imageUrl: '/pages/resource/images/share.png',
      success: function (res) {console.log("转发朋友圈成功", res)},
      fail: function (res) {
        // 转发失败
        console.log("用户点击了取消", res)
      } 
    }
  },
  onReachBottom: function() { //上拉刷新
    var that = this
    that.getInvoiceData()
  },
  getInvoiceData: function() { //获取发票数据
    var that = this
    if(!that.data.lodding && !that.data.noData){
      console.log("上拉刷新")
      that.showLodding()
      // 判断是否登录以及是否是免费用户，他们则死数据进行加载，
      // 否则就加载后台api，如果首次获取为空，则展示背景图片
      var wxUserId = app.globalData.wxUserId
      if(wxUserId != null && wxUserId != ''){
        that.getHttpInvoiceData()
      } else { //未登录
        that.getLocalInvoiceData()
      }
    }
  },
  getSearchDate: function(){ // 获取搜索年月
    var that = this 
    var datas = ''
    var month = that.data.searchDateMonthTab
    var year = that.data.searchDateTab
    if (month != null) {
      var now = new Date().getFullYear()
      if (year == '0') {
        now = Number.parseInt(now) - 1
      }
      datas = now + "-" + util.formatMonthNumber(Number.parseInt(month) + 1)
    }
    return datas;
  },
  getHttpInvoiceData: function() { //api获取发票数据
    var that = this
    var offset = that.data.invoiceList.length
    var searchDate = that.getSearchDate()
    console.log("search date:" + searchDate)
    var data = {
      userId: app.globalData.wxUserId,
      offset: offset,
      invoiceDateYM: searchDate,
      type: that.data.invoiceTab
    }
    app.http.post('/wechat/findInvoiceList',data).then(res =>{
      var noData = false
      var invoiceImg = false
      if(res.status == '200'){
        var listData = res.data
        if(listData.length < 5){ // 获取数据数 小于分页数则表示无数据了
          noData = true
        }
        listData = that.data.invoiceList.concat(listData)
        if(listData.length == 0){ //获取总长度为0 则展示背景图
          invoiceImg = true
        }
        that.setData({
          invoiceImg: invoiceImg,
          invoiceList: listData,
          lodding: false,
          noData: noData,
          swiper_height: listData.length * 86
        })
      } else {
        that.setData({
          lodding: false,
          noData: noData,
        })
      }
    })
  },
  getLocalInvoiceData: function() { //本地获取发票数据
    var that = this
    var i = that.data.invoiceList.length
    if(i > 5){
      wx.showModal({
        title: '暂未登录',
        content: '是否去授权登录',
        success: function (res) {
          if (!res.cancel) {
             //点击确定
             wx.reLaunch({
              url: '/pages/wechat/wechat',
            })
          }
       },
       fail: function (res) { },//接口调用失败的回调函数
      })
      that.setData({
        lodding: false,
        noData: true,
      })
    } else {
      setTimeout(() => {
        var listData = []
        if(that.data.invoiceTab.toString() == '0'){
          var idata = [{
            invoiceId: 0,
            invoiceName: '深圳市上佳科技有限公司',
            invoiceAmount: 240,
            invoiceDate: '2019-12-03',
            invoiceType: '建筑'
          },{
            invoiceId: 0,
            invoiceName: '深圳市上佳科技有限公司',
            invoiceAmount: 240,
            invoiceDate: '2019-12-03',
            invoiceType: '建筑'
          },{
            invoiceId: 0,
            invoiceName: '深圳市上佳科技有限公司',
            invoiceAmount: 240,
            invoiceDate: '2019-12-03',
            invoiceType: '建筑'
          }]
          listData = that.data.invoiceList.concat(idata)
        }
        var noData = false
        var invoiceImg = false
        if(listData.length > 15){
          noData = true
        }
        if(listData.length == 0){ //获取总长度为0 则展示背景图
          invoiceImg = true
        }
        that.setData({
          invoiceImg: invoiceImg,
          invoiceList: listData,
          lodding: false,
          noData: noData,
          swiper_height: listData.length * 95
        })
      }, 1000 * 3);
    }
    
  },
  // pageScrollToButton: function(el){ //滚动滚动条
  //   wx.createSelectorQuery().select('#'+el).boundingClientRect(function (rect) {
  //     // 使页面滚动到底部
  //      wx.pageScrollTo({
  //          scrollTop: rect.bottom
  //      })
  //  }).exec()
  // },
  showLodding: function() { // 显示列表数据加载动画
    var that = this
    if(!that.data.lodding) {
      that.setData({
        lodding: true,
        noData: false
      })
    }
  },
  hideLodding: function() { //隐藏列表数据加载动画
    that.setData({
      lodding: false
    })
  },
  goVip: function() {
    // 判断是否登录，未登录则跳转登录页面
    var wxUserId = app.globalData.wxUserId
    if(wxUserId != null && wxUserId != ''){
      if(app.globalData.platform == "ios" && !app.globalData.iosPayStatus){
        wx.showToast({
          title: '由于相关规范，iOS功能暂不可用',
          icon: 'none',
          duration: 3000
        })
      } else {
        wx.navigateTo ({
          url: '../vip/vip'
        })
      }
    } else { // 跳转去登录页面
      wx.reLaunch({
        url: '/pages/wechat/wechat?path=vip',
      })
    }
  },
  goDetail: function(e) {
    var invoiceId = e.currentTarget.dataset.id
    wx.navigateTo ({
      url: '../detail/detail?invoiceId=' + invoiceId
    })
  },
  singlePay: function() {
    // 判断是否登录，未登录则跳转登录页面
    var wxUserId = app.globalData.wxUserId
    if(wxUserId != null && wxUserId != ''){
      wx.navigateTo ({
        url: '../singlePay/singlePay'
      })
    } else { // 跳转去登录页面
      wx.reLaunch({
        url: '/pages/wechat/wechat',
      })
    }
  },
  getSingPayStatus: function() { //获取单次购买状态
    var that = this
    app.http.get('/wechat/getSingPayStatus').then(res =>{
      if(res.status == '200'){ //打开单次支付购买入口
        that.setData({singPayStatus: true})
      } else {
        that.setData({singPayStatus: false})
      }
    })
  },
  getInvoice: function() { // 获取发票按钮点击事件
    var that = this
    // 判断是否登录，未登录获取本地数据，免费用户不能获取数据，包次以及vip邮箱获取
    var wxUserId = app.globalData.wxUserId
    if(wxUserId != null && wxUserId != ''){
      var wxUserType = app.globalData.wxUserType
      if(wxUserType == '1'){ // 免费用户
        if(app.globalData.platform == "ios" && !app.globalData.iosPayStatus){
          wx.showToast({
            title: '会员已到期！！！',
            icon: 'none',
            duration: 3000
          })
        } else {
          //点击则弹出身份选择框
          that.setData({showChooseDialog: true})
        }
         
      } else { // 包次或vip用户
        // 获取发票
        that.mailGetInvoice();
      }
    } else { // 未登录用户
      if(!that.data.lodding){
        that.showLodding()
        that.getLocalInvoiceData()
      }
    }
  },
  openSearch: function() { //打开搜索框
    var that = this
    wx.setNavigationBarColor({
      frontColor: '#ffffff', // 必写项
      backgroundColor: '#ffffff', // 必写项
      animation: { // 可选项
          duration: 500,
          timingFunc: 'easeIn'
      }
    })
    that.setData({
      search: true
    })
  },
  closeSearch: function() { //关闭搜索框
    var that = this
    wx.setNavigationBarColor({
      frontColor: '#ffffff', // 必写项
      backgroundColor: '#3B83FC', // 必写项
      animation: { // 可选项
          duration: 500,
          timingFunc: 'easeIn'
      }
    });
    that.setData({
      searchDateMonthTab: null,
      search: false
    })
  },
  searchDateYear: function(e) { //开票日期年份点击事件
    var that = this;
    console.log("search year:" + e.target.dataset.current)
    if(this.data.searchDateTab === e.target.dataset.current) {
      that.setData({
        searchDateMonthTab: null
      })
      return false;
    } else {
      that.setData({
        searchDateTab: e.target.dataset.current
      })
    }
  },
  searchDateMonth: function(e) { //开票日期月份点击事件
    var that = this;
    console.log("search month:" + e.target.dataset.current)
    if(that.data.searchDateMonthTab === e.target.dataset.current) {
      that.setData({searchDateMonthTab: null});
    } else {
      that.setData({searchDateMonthTab: e.target.dataset.current});
    }
  },
  serchDateChange: function(e) { //开票日期滑动切换事件
    var that = this;
    that.setData({searchDateTab: e.detail.current,searchDateMonthTab: null});
  },
  closeIntroduce: function () { //关闭介绍海报弹窗
    var that = this;
    that.setData({
      showIntroduceDialog: false,
      showChooseDialog: true
    });
  },
  searchMonth: function() { //搜索确认按钮
    var that = this
    var month = that.data.searchDateMonthTab
    if (month != null) {
      that.setData({ 
        search: false,
        invoiceImg: false,
        noData: false,
        invoiceList: []
      });
    } else {
      that.setData({ 
        search: false,
        invoiceImg: false,
        noData: false,
        invoiceList: []
      });
    }
    wx.setNavigationBarColor({ // 调整导航栏颜色
      frontColor: '#ffffff', // 必写项
      backgroundColor: '#3B83FC', // 必写项
      animation: { // 可选项
          duration: 500,
          timingFunc: 'easeIn'
      }
    });
    that.getInvoiceData()
  },
  closeChoose() { //关闭初始身份选择 弹框
    var that = this
    that.setData({
      showChooseDialog: false
    });
  },
  swichNav: function(e) {//  发票列表tab切换逻辑
    var that = this;
    console.log("tab按钮点击切换！！！")
    if(that.data.invoiceTab.toString() === e.target.dataset.current && that.data.invoiceImg) {
      return false;
    } else {
      that.setData({
        invoiceImg: false,
        invoiceTab: e.target.dataset.current,
        noData: false,
        invoiceList: []
      })
      that.getInvoiceData()
    }
  },
  bindSwiperChange: function(e) { //发票列表 选项切换事件
    var that = this;
    console.log("发票列表切换！！！")
    that.setData({ 
      invoiceImg: false,
      invoiceTab: e.detail.current,
      noData: false,
      invoiceList: []
    });
    that.getInvoiceData()
  },
  onPageScroll: function(e) { //发票列表滚动事件
    let that = this;
    if (e.scrollTop > that.data.topxp) {
      if(that.data.top_swiper === ''){
        that.setData({
          top_swiper: "topnav"
        })
      }
    } else {
      if(that.data.top_swiper !== ''){
        that.setData({
          top_swiper: ""
        })
      }
    }
  },
  mailGetInvoice: function() { //邮箱获取邮件
    var that = this
    var wxUserId = app.globalData.wxUserId
    app.http.get('/wechat/getNewInvoice?userId=' + wxUserId).then(res =>{
      if(res.status == '200'){
        if(res.data != null && res.data != ''){ //上次获取还在后台进行中
          console.log('邮箱获取发票-上次获取还在后台进行中：' + res.data)
          that.setData({
            showBallDialog: true
          })
          var ballLoad = load.initLoad('canvasArcCir', 0);
          this.ballLoad = ballLoad
          getInvoiceStatus(ballLoad, wxUserId, res.data)
        } else { // 重新获取，需要定时调度查询状态
          that.setData({
            showBallDialog: true
          })
          //创建并返回绘图上下文context对象。
          var ballLoad = load.initLoad('canvasArcCir', 0);
          this.ballLoad = ballLoad
          getInvoiceStatus(ballLoad,wxUserId, '')
        }
      } else if(res.status == '555'){
        wx.showModal({
          title: res.msg,
          content: '是否去添加邮箱信息',
          success: function (res) {
            if (!res.cancel) {
               wx.navigateTo({
                url: '/pages/login/login',
              })
            }
         },
        })
      } else if(res.status == '556'){
        wx.showModal({
          title: res.msg,
          content: '是否去添加邮箱授权码',
          success: function (res) {
            if (!res.cancel) {
              wx.navigateTo({
                url: '/pages/authorization/authorization',
              })
            }
         },
        })
      } else if(res.status == '557'){
        wx.showModal({
          title: res.msg,
          content: '是否去购买VIP',
          success: function (res) {
            if (!res.cancel) {
              wx.navigateTo ({
                url: '../vip/vip'
              })
            }
         },
        })
      } else if(res.status == '558'){
        wx.showModal({
          title: res.msg,
          content: '是否去购买VIP',
          success: function (res) {
            if (!res.cancel) {
              wx.navigateTo ({
                url: '../vip/vip'
              })
            }
         },
        })
      } else if(res.status == '559'){
        wx.showModal({
          title: res.msg,
          content: '是否去购买VIP',
          success: function (res) {
            if (!res.cancel) {
              wx.navigateTo ({
                url: '../vip/vip'
              })
            }
         },
        })
      }else {
        wx.showToast({
          title: res.msg,
          icon: "none"
        })
      }
    })
    function getInvoiceStatus(c, wxUserId, status){ //获取邮件状态
      if (status == null || status == ''){
        c.addProgress(20)
        that.setData({ballText: "邮箱信息加载中"})
        setTimeout(getInvoiceStatus, 3 * 1000, c, wxUserId, '0');
      } else { 
        app.http.get('/wechat/getInvoiceStatus?userId=' + wxUserId).then(res =>{
          if(res.status == '200'){
            var data = res.data
            if(data.result){
              var newStatus = parseInt(data.status);
              if (newStatus == 1) {
                  c.addProgress(40)
                  that.setData({ballText: "连接邮箱中"})
              } else if (newStatus == 2) {
                  c.addProgress(60)
                  that.setData({ballText: "获取邮件中"})
              } else if (newStatus == 3) {
                  c.addProgress(80)
                  that.setData({ballText: "解析邮件中"})
              } else if (newStatus == 4) {
                  c.addProgress(100)
                  that.setData({ballText: "获取完成，共获取" + data.invoice + "封邮件"})
                  setTimeout(function () {
                    console.log(3333333333)
                    c.clearBallTimeout()
                    //刷新列表
                    // $("#tbTable").bootstrapTable('refresh', init);
                  },3 * 1000);
              }
              if (newStatus != 4) { //未结束则一直轮询
                setTimeout(getInvoiceStatus, 3 * 1000, c, wxUserId, newStatus);
              }
            } else { // 解析邮件异常
              var newStatus = parseInt(data.status);
              // 添加错误信息
              if (newStatus == 1) {
                c.addProgress(40)
                that.setData({ballText: "连接邮箱失败"})
              } else if (newStatus == 2) {
                c.addProgress(60)
                that.setData({ballText: "获取邮件失败"})
              } else if (newStatus == 3) {
                c.addProgress(80)
                that.setData({ballText: "解析邮件失败"})
              } else if (newStatus == 4) {
                c.addProgress(99)
                that.setData({ballText: "保存邮件失败"})
              }
              setTimeout(function () {
                c.clearBallTimeout()
              },5 * 1000);
            }
          }
        })
      }
    }
  },
  ballClose: function() { //关闭加载
    var that = this
    this.ballLoad.clearBallTimeout() //关闭水球动画 避免在占用内存
    that.setData({
      showBallDialog: false,
      invoiceImg: false,
      noData: false,
      invoiceList: []
    })
    that.getInvoiceData()
  }
})
